/*
 * Copyright 2017-2020 吴学文 and java110 team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.java110.mall.acct.smo.impl;


import com.java110.core.annotation.Java110Transactional;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.gold.GoldDetailDto;
import com.java110.dto.shop.ShopDto;
import com.java110.dto.storeOrder.StoreOrderLedgerAcctDto;
import com.java110.intf.acct.IGoldDetailOrderV1InnerServiceSMO;
import com.java110.intf.acct.IGoldDetailV1InnerServiceSMO;
import com.java110.intf.shop.IShopInnerServiceSMO;
import com.java110.intf.user.IWuyeV1InnerServiceSMO;
import com.java110.mall.acct.dao.IGoldV1ServiceDao;
import com.java110.intf.acct.IGoldV1InnerServiceSMO;
import com.java110.dto.gold.GoldDto;
import com.java110.po.gold.GoldDetailPo;
import com.java110.po.gold.GoldPo;
import com.java110.po.gold.GoldDetailOrderPo;
import com.java110.po.user.PropertyOwnerAcctDto;
import com.java110.po.user.PropertyOwnerDto;
import com.java110.utils.lock.DistributedLock;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.core.base.smo.BaseServiceSMO;
import com.java110.dto.PageDto;
import com.java110.utils.util.ListUtil;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * 类表述： 服务之前调用的接口实现类，不对外提供接口能力 只用于接口建调用
 * add by 吴学文 at 2024-04-28 00:56:29 mail: 928255095@qq.com
 * open source address: https://gitee.com/wuxw7/MicroCommunity
 * 官网：http://www.homecommunity.cn
 * 温馨提示：如果您对此文件进行修改 请不要删除原有作者及注释信息，请补充您的 修改的原因以及联系邮箱如下
 * // modify by 张三 at 2021-09-12 第10行在某种场景下存在某种bug 需要修复，注释10至20行 加入 20行至30行
 */
@RestController
public class GoldV1InnerServiceSMOImpl extends BaseServiceSMO implements IGoldV1InnerServiceSMO {

    @Autowired
    private IGoldV1ServiceDao goldV1ServiceDaoImpl;

    @Autowired
    private IGoldDetailV1InnerServiceSMO goldDetailV1InnerServiceSMOImpl;

    @Autowired
    private IGoldDetailOrderV1InnerServiceSMO goldDetailOrderV1InnerServiceSMOImpl;

    @Autowired
    private IWuyeV1InnerServiceSMO wuyeV1InnerServiceSMOImpl;

    @Autowired
    private IShopInnerServiceSMO shopInnerServiceSMOImpl;


    @Override
    public int saveGold(@RequestBody GoldPo goldPo) {
        int saveFlag = goldV1ServiceDaoImpl.saveGoldInfo(BeanConvertUtil.beanCovertMap(goldPo));
        return saveFlag;
    }

    @Override
    public int updateGold(@RequestBody GoldPo goldPo) {
        int saveFlag = goldV1ServiceDaoImpl.updateGoldInfo(BeanConvertUtil.beanCovertMap(goldPo));
        return saveFlag;
    }

    @Override
    public int deleteGold(@RequestBody GoldPo goldPo) {
        goldPo.setStatusCd("1");
        int saveFlag = goldV1ServiceDaoImpl.updateGoldInfo(BeanConvertUtil.beanCovertMap(goldPo));
        return saveFlag;
    }

    @Override
    public List<GoldDto> queryGolds(@RequestBody GoldDto goldDto) {

        //校验是否传了 分页信息

        int page = goldDto.getPage();

        if (page != PageDto.DEFAULT_PAGE) {
            goldDto.setPage((page - 1) * goldDto.getRow());
        }

        List<GoldDto> golds = BeanConvertUtil.covertBeanList(goldV1ServiceDaoImpl.getGoldInfo(BeanConvertUtil.beanCovertMap(goldDto)), GoldDto.class);

        return golds;
    }


    @Override
    public int queryGoldsCount(@RequestBody GoldDto goldDto) {
        return goldV1ServiceDaoImpl.queryGoldsCount(BeanConvertUtil.beanCovertMap(goldDto));
    }

    @Override
    @Java110Transactional
    public int preStoreGold(@RequestBody StoreOrderLedgerAcctDto storeOrderLedgerAcctDto) {


        if (StringUtil.isEmpty(storeOrderLedgerAcctDto.getPayAcctId())) {
            throw new IllegalArgumentException("账户ID为空");
        }
        //开始枷锁
        String requestId = DistributedLock.getLockUUID();
        String key = storeOrderLedgerAcctDto.getPayAcctId();
        GoldDto goldDto = null;
        List<GoldDto> goldDtos = null;
        int flag;
        try {
            DistributedLock.waitGetDistributedLock(key, requestId);
            goldDto = new GoldDto();
            goldDto.setGoldId(storeOrderLedgerAcctDto.getPayAcctId());
            goldDtos = queryGolds(goldDto);
            if (ListUtil.isNull(goldDtos)) {
                throw new IllegalArgumentException("小区金币账户不存在");
            }
            //在账户增加
            double amount = Double.parseDouble(goldDtos.get(0).getAmount());
            BigDecimal amountBig = new BigDecimal(amount);
            amount = amountBig.add(new BigDecimal(Double.parseDouble(storeOrderLedgerAcctDto.getAmount()))).doubleValue();
            GoldPo goldPo = new GoldPo();
            goldPo.setGoldId(goldDtos.get(0).getGoldId());
            goldPo.setAmount(amount + "");
            flag = updateGold(goldPo);
            if (flag < 1) {
                throw new IllegalArgumentException("更新账户失败");
            }
        } finally {
            DistributedLock.releaseDistributedLock(requestId, key);
        }

        GoldDetailPo goldDetailPo = new GoldDetailPo();
        goldDetailPo.setDetailType(GoldDetailDto.DETAIL_TYPE_IN);
        goldDetailPo.setAmount(storeOrderLedgerAcctDto.getAmount());
        goldDetailPo.setOrderId(storeOrderLedgerAcctDto.getOrderId());
        goldDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId("11"));
        goldDetailPo.setGoldId(storeOrderLedgerAcctDto.getPayAcctId());
        goldDetailPo.setCommunityName(goldDtos.get(0).getCommunityName());
        goldDetailPo.setRemark("购买商品赠送的抵扣金");
        goldDetailPo.setCommunityId(goldDtos.get(0).getCommunityId());

        goldDetailV1InnerServiceSMOImpl.saveGoldDetail(goldDetailPo);


        PropertyOwnerDto propertyOwnerDto = new PropertyOwnerDto();
        propertyOwnerDto.setOwnerId(storeOrderLedgerAcctDto.getSaveObjId());
        propertyOwnerDto = wuyeV1InnerServiceSMOImpl.getOwner(propertyOwnerDto);


        PropertyOwnerAcctDto propertyOwnerAcctDto = new PropertyOwnerAcctDto();
        propertyOwnerAcctDto.setOwnerId(propertyOwnerDto.getOwnerId());
        propertyOwnerAcctDto.setOwnerTel(propertyOwnerDto.getOwnerTel());
        propertyOwnerAcctDto.setAmount(Double.parseDouble(storeOrderLedgerAcctDto.getAmount()));
        propertyOwnerAcctDto.setCommunityId(propertyOwnerDto.getCommunityId());
        ResultVo resultVo = wuyeV1InnerServiceSMOImpl.prestoreAccount(propertyOwnerAcctDto);

        ShopDto shopDto = new ShopDto();
        shopDto.setShopId(storeOrderLedgerAcctDto.getShopId());
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        if (ListUtil.isNull(shopDtos)) {
            throw new IllegalArgumentException("商铺不存在");
        }


        //todo 送到业主账户
        GoldDetailOrderPo goldDetailOrderPo = new GoldDetailOrderPo();
        goldDetailOrderPo.setStateMsg(resultVo.getMsg());
        goldDetailOrderPo.setState(resultVo.getCode() + "");
        goldDetailOrderPo.setOrderId(storeOrderLedgerAcctDto.getOrderId());
        goldDetailOrderPo.setDetailId(goldDetailPo.getDetailId());
        goldDetailOrderPo.setShopName(shopDtos.get(0).getShopName());
        goldDetailOrderPo.setGoldId(storeOrderLedgerAcctDto.getPayAcctId());
        goldDetailOrderPo.setRemark("同步业主账户");
        goldDetailOrderPo.setPersonName(propertyOwnerDto.getOwnerName());
        goldDetailOrderPo.setPersonId(propertyOwnerDto.getOwnerId());
        goldDetailOrderPo.setPersonTel(propertyOwnerDto.getOwnerTel());
        goldDetailOrderPo.setGdoId(GenerateCodeFactory.getGeneratorId("11"));
        goldDetailOrderPo.setShopId(shopDtos.get(0).getShopId());

        goldDetailOrderV1InnerServiceSMOImpl.saveGoldDetailOrder(goldDetailOrderPo);


        return 1;
    }

    @Override
    public int withholdGold(@RequestBody GoldDetailPo goldDetailPo) {


        if (StringUtil.isEmpty(goldDetailPo.getGoldId())) {
            throw new IllegalArgumentException("金币ID为空");
        }
        //开始枷锁
        String requestId = DistributedLock.getLockUUID();
        String key = goldDetailPo.getGoldId();
        GoldDto goldDto = null;
        List<GoldDto> goldDtos = null;
        int flag;
        try {
            DistributedLock.waitGetDistributedLock(key, requestId);
            goldDto = new GoldDto();
            goldDto.setGoldId(goldDetailPo.getGoldId());
            goldDtos = queryGolds(goldDto);
            if (ListUtil.isNull(goldDtos)) {
                throw new IllegalArgumentException("小区金币账户不存在");
            }
            //在账户增加
            double amount = Double.parseDouble(goldDtos.get(0).getAmount());
            BigDecimal amountBig = new BigDecimal(amount);
            amount = amountBig.subtract(new BigDecimal(Double.parseDouble(goldDetailPo.getAmount()))).doubleValue();
            GoldPo goldPo = new GoldPo();
            goldPo.setGoldId(goldDtos.get(0).getGoldId());
            goldPo.setAmount(amount + "");
            flag = updateGold(goldPo);
            if (flag < 1) {
                throw new IllegalArgumentException("更新账户失败");
            }
        } finally {
            DistributedLock.releaseDistributedLock(requestId, key);
        }

        goldDetailPo.setDetailType(GoldDetailDto.DETAIL_TYPE_OUT);
        if(StringUtil.isEmpty(goldDetailPo.getOrderId())){
            goldDetailPo.setOrderId("-1");
        }
        if(StringUtil.isEmpty(goldDetailPo.getDetailId())){
            goldDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId("11"));
        }

        goldDetailPo.setCommunityId(goldDtos.get(0).getCommunityId());
        goldDetailPo.setCommunityName(goldDtos.get(0).getCommunityName());
        if(StringUtil.isEmpty(goldDetailPo.getRemark())){
            goldDetailPo.setRemark("购买商品赠送的抵扣金");
        }

        goldDetailV1InnerServiceSMOImpl.saveGoldDetail(goldDetailPo);

        return 0;
    }

}
